package com.joe.core;

import com.joe.entity.Po.ParamType;
import com.joe.entity.exceptions.TypeNotMatchException;
import com.joe.utils.BeanUtils;
import com.joe.utils.New;

import java.lang.reflect.InvocationTargetException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

/**
 * Created by joe on 2018/12/2
 */
public class ResultMapper {

    public Object doMapping(ParamType type, ResultSet resultSet) throws IllegalAccessException, InstantiationException, SQLException, TypeNotMatchException, InvocationTargetException, NoSuchMethodException {
        Collection collection = null;
        Class<?> objType = type.getObjType();

        if (type.isCollection()) {
            collection = New.newCollection(type.getCollectionType());
        }

        int count = getRows(resultSet);
        if (collection == null && count > 1) {
            throw new TypeNotMatchException("The select result does not match the return type! select count ->" + count);
        }

        while (resultSet.next()) {
            Object item = objType.newInstance();

            String[] names = BeanUtils.getPropertyNames(objType);

            for (String name : names) {
                Object value = resultSet.getObject(name);

                if (value != null) {
                    BeanUtils.setValue(item, name, value);
                }
            }

            if (collection == null) {
                return item;
            }
            collection.add(item);

        }
        return collection;
    }

    /**
     * 获取一共有多少条记录
     */
    private int getRows(ResultSet rs) throws SQLException {
        rs.last();
        int result = rs.getRow();
        rs.beforeFirst();
        return result;
    }

}
